package jmine.tec.cluster.heartbeat;

import java.util.concurrent.Callable;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import bancosys.tec.persist.controller.TransactionalController;
import bancosys.tec.rtm.exception.ExceptionPersister;

/**
 * Classe que chama o método agendado de validação de nós para um cluster.
 * 
 * @author ricardo
 * 
 */
public class ValidateNodesJob extends QuartzJobBean {

	private static final Logger LOG = Logger.getLogger(ValidateNodesJob.class);

	private HeartBeatMasterIdentificator identificator;

	private TransactionalController controller;

	private ExceptionPersister exceptionPersister;

	/**
	 * Setter do identificador de nó mestre.
	 * 
	 * @param identificator
	 *            o identificador
	 */
	public void setIdentificator(HeartBeatMasterIdentificator identificator) {
		this.identificator = identificator;
	}

	/**
	 * Setter do controller.
	 * 
	 * @param controller
	 *            o controller
	 */
	public void setController(TransactionalController controller) {
		this.controller = controller;
	}

	/**
	 * Setter do persister.
	 * 
	 * @param exceptionPersister
	 *            o persister
	 */
	public void setExceptionPersister(ExceptionPersister exceptionPersister) {
		this.exceptionPersister = exceptionPersister;
	}

	/**
	 * Executa o método de validação de nós agendado no quartz.
	 * 
	 * @param context
	 *            o contexto do quartz.
	 * @throws JobExecutionException
	 *             em caso inesperado.
	 */
	@Override
	public void executeInternal(JobExecutionContext context)
			throws JobExecutionException {

		LOG.debug("executing validate nodes");

		try {
			this.controller.executeTransacted(new Callable<Void>() {
				public Void call() throws Exception {
					ValidateNodesJob.this.identificator.validateNodes();
					return null;
				}
			});
		} catch (Exception e) {
			this.exceptionPersister.monitor(e);
		}
	}

}
